package com.shaomengjie.smjmvp.view.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Handler;
import android.os.Message;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.shaomengjie.smjmvp.R;
import com.shaomengjie.smjmvp.bean.UserBean;
import com.shaomengjie.smjmvp.contract.LoginContract;
import com.shaomengjie.smjmvp.presenter.LoginPresenter;
import com.shaomengjie.smjmvp.utils.AnimUtils;
import com.shaomengjie.smjmvp.utils.ToastUtils;
import com.shaomengjie.smjmvp.view.core.BaseActivity;
import com.shaomengjie.smjmvp.widget.CircleImageView;

public class LoginActivity extends BaseActivity implements LoginContract.View, View.OnClickListener {
    private LoginPresenter mPresenter;
    private TextView mTextView;
    private AnimationDrawable backgroundAnim,headOutAnim,headInAnim;
    private RelativeLayout mActivityLogin;
    private AutoCompleteTextView mEmailView;
    private RelativeLayout mFloatButton;
    private RelativeLayout mBackGroundRL,mLoginRL,mRegisterRL;
    private LinearLayout mLoginLL;
    private boolean flag = false;
    private long timestamp;
    private CircleImageView mOutCircleView,mInCircleView,mCircleImageView;
    private Button mLoginButton,mRegisterButton;
    private EditText mPassWord;

    @Override
    protected void setContentView() {
        setContentView(R.layout.activity_login);
    }

    @Override
    protected void initView() {
        findViwe();
        new LoginPresenter(this);
        requestLogion();
    }

    private void findViwe() {
        mEmailView = (AutoCompleteTextView) findViewById(R.id.email);
        mPassWord = (EditText) findViewById(R.id.password);
        mFloatButton = (RelativeLayout) findViewById(R.id.floationgActionButton);
        mRegisterRL = (RelativeLayout) findViewById(R.id.register);
        mLoginRL = (RelativeLayout) findViewById(R.id.relativeLayout2);
        mBackGroundRL = (RelativeLayout) findViewById(R.id.relativeLayout3);
        mLoginLL = (LinearLayout) findViewById(R.id.mLoginLL);
        mOutCircleView = (CircleImageView) findViewById(R.id.mOutCircleView);
        mInCircleView = (CircleImageView) findViewById(R.id.mInCircleView);
        mCircleImageView = (CircleImageView) findViewById(R.id.mCircleImageView);
        mLoginButton = (Button) findViewById(R.id.login_button);
        mActivityLogin = (RelativeLayout) findViewById(R.id.activity_login);
        backgroundAnim = (AnimationDrawable) mActivityLogin.getBackground();
        headOutAnim = (AnimationDrawable) mOutCircleView.getBackground();
        headInAnim = (AnimationDrawable) mInCircleView.getBackground();
        setHeadAnim(backgroundAnim);
        setHeadAnim(headOutAnim);
        setHeadAnim(headInAnim);
        setClick();
    }

    private void setHeadAnim(AnimationDrawable anim) {
        anim.setEnterFadeDuration(1000);
        anim.setExitFadeDuration(2000);
    }

    private void setClick() {
        mFloatButton.setOnClickListener(this);
        mLoginButton.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.floationgActionButton:
                cutLoginAndRegister();
                break;
            case R.id.login_button:
                logion();
                break;
        }
    }

    private void logion() {
        if (attemptLogin()) {
            showProgress();
            mHandler.sendEmptyMessageDelayed(0,2000);
        }
    }
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    closeProgress();
                    Intent intent = new Intent(LoginActivity.this,MainActivity.class);
                    startActivity(intent);
                    break;
            }
        }
    };
    private boolean attemptLogin() {
        View focusView = null;
        String userName = mEmailView.getText().toString().trim();
        String password = mPassWord.getText().toString().trim();
        if (TextUtils.isEmpty(userName)) {
            mEmailView.setError(getString(R.string.error_field_required));
            focusView = mEmailView;
            focusView.requestFocus();
            return false;
        } else if (!isEmailValid(userName)) {
            mEmailView.setError(getString(R.string.error_invalid_email));
            focusView = mEmailView;
            focusView.requestFocus();
            return false;
        }
        if (TextUtils.isEmpty(password)) {
            mPassWord.setError(getString(R.string.error_empty_password));
            focusView = mPassWord;
            focusView.requestFocus();
            return false;
        }else if (!isPasswordValid(password)){
            mPassWord.setError(getString(R.string.error_invalid_password));
            focusView = mPassWord;
            focusView.requestFocus();
            return false;
        }
        return true;
    }

    private boolean isPasswordValid(String password) {
        //TODO: Replace this with your own logic
        return password.length() > 4;
    }
    private boolean isEmailValid(String email) {
        //TODO: Replace this with your own logic
        //return email.contains("@");
        return true;
    }

    private void cutLoginAndRegister() {
        hideKeyboard();
        if (!flag) {
            //注册页面展开
            registerUpfold();
            //按钮进入页面
            buttonEnterPage();

        } else {
            //登陆页面展开
            loginUpfold();
            //按钮离开页面
            buttonOutPage();
        }
        flag = !flag;
    }

    private void buttonOutPage() {
        AnimUtils.setButtonOutPage(mFloatButton);
    }

    private void loginUpfold() {
        mLoginLL.setVisibility(View.VISIBLE);
        mRegisterRL.setVisibility(View.GONE);
        int centerX = mLoginRL.getLeft();
        int centerY = mLoginRL.getTop();
        float endRadius = (float) Math.hypot(mRegisterRL.getWidth(), mRegisterRL.getHeight());
        AnimUtils.setRegisterUpfold(mLoginRL,centerX,centerY,0f,endRadius);
    }

    private void buttonEnterPage() {
        AnimUtils.setButtonEnterPage(mFloatButton);
    }

    private void registerUpfold() {
        mLoginLL.setVisibility(View.GONE);
        mRegisterRL.setVisibility(View.VISIBLE);
        int centerX = (mFloatButton.getLeft() + mFloatButton.getRight()) / 2;
        int centerY = (mFloatButton.getTop() + mFloatButton.getBottom()) / 2;
        float startRadius = (float) mFloatButton.getWidth() / 2;
        float endRadius = (float) Math.hypot(mRegisterRL.getWidth(), mRegisterRL.getHeight());
        AnimUtils.setRegisterUpfold(mRegisterRL,centerX,centerY,startRadius,endRadius);
    }


    @Override
    protected void initData(Bundle savedInstanceState) {

    }

    @Override
    public void requestLogion() {
        mPresenter.requestLogion("17601399159","123456",this);
    }

    @Override
    public void showText(UserBean userBean) {
        mTextView.setText(userBean.getData().getUser_info().getMobile());
    }

    @Override
    public void setPresenter(Object presenter) {
        mPresenter = (LoginPresenter) presenter;
    }
    @Override
    protected void onResume() {
        super.onResume();
        stratAnim(backgroundAnim,true);
        stratAnim(headOutAnim,true);
        stratAnim(headInAnim,true);
    }

    private void stratAnim(AnimationDrawable anim, boolean b) {
        if (anim!=null&&!anim.isRunning()){
            if (b){
                anim.start();
            }else {
                anim.stop();
            }
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        stratAnim(backgroundAnim,false);
        stratAnim(headOutAnim,false);
        stratAnim(headInAnim,false);
    }
    private void hideKeyboard() {
        View view = getCurrentFocus();
        if (view != null) {
            ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).
                    hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }
    @Override
    public void onBackPressed() {
        if (System.currentTimeMillis() - timestamp < 2000) {
            super.onBackPressed();
        } else {
            ToastUtils.showToast(getBaseContext(),"再点一次退出应用哦");
            timestamp = System.currentTimeMillis();
        }
    }
}
